package de.dailab.prefgen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.dailab.prefgen.INameMapping.TYPE;


import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class BooleanEnumLeaf implements ILeafFactory {

	private static final String TRUE_EXPR = "(true|yes|ja)";

	@Override
	public boolean shouldGenerate(Class type) {
		return (type.isEnum() && type.getEnumConstants().length == 2 && (type
				.getEnumConstants()[0].toString().matches(TRUE_EXPR) || type
				.getEnumConstants()[0].toString().matches(TRUE_EXPR)))
				|| Boolean.class.isAssignableFrom(type);
	}

	@Override
	public Preference generate(Object superObject, Method callingMethod,
			PreferenceActivity context, INameMapping nameMapping) {

		CheckBoxPreference box = new CheckBoxPreference(context);

		box.setKey(nameMapping.toHumanReadable(callingMethod,superObject, TYPE.KEY));
		box.setTitle(nameMapping.toHumanReadable(callingMethod,superObject, TYPE.TITLE));
		box.setSummary(nameMapping.toHumanReadable(callingMethod,superObject,
				TYPE.DESCRIPTION));
		box.setPersistent(false);
		
		box.setOnPreferenceChangeListener(new BooleanLeafPreferenceChangeListener(
				superObject, callingMethod, nameMapping));

		try {

			Class type = callingMethod.getReturnType();
			Object obj = callingMethod.invoke(superObject, null);

			boolean enabled = false;

			// if it is unset it is not true
			if (obj != null) {
				// is Enum
				if (type.isEnum()) {

				
					// it is true
					if (obj.toString().matches(TRUE_EXPR)) {
						enabled = true;
					} else {
						// see if it is the first Element
						if (type.getEnumConstants()[0].equals(obj)) {
							enabled = true;
						}
					}
				} else {
					// it is a Boolean
					enabled = (Boolean) obj;
				}

			}
			box.setChecked(enabled);
			
			return box;

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return null;

	}
	

	class BooleanLeafPreferenceChangeListener extends OnLeafPrefernceChangedListener {

		private final Method getter2;


		public BooleanLeafPreferenceChangeListener(Object superObject,
				Method getter, INameMapping nameMapper) {
			super(superObject, getter, nameMapper);
			getter2 = getter;
		}

		
		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			Class<?> type = getter2.getReturnType();
			if (type.isEnum()){
				Object[] enumConstants=type.getEnumConstants();
				if (enumConstants[0].toString().matches(TRUE_EXPR) == newValue.toString().matches(TRUE_EXPR)){
					newValue = enumConstants[0];
				} else {
					newValue = enumConstants[1];
				}
			}
			return super.onPreferenceChange(preference, newValue);
		}
		
		
		
	}

}
